const network = require('./network.js')
const LOGIN_INFO = 'LOGIN_INFO'
const app = getApp() ;
const saveLoginInfo = (info)=>{
  try {
    wx.setStorageSync(LOGIN_INFO, info)
    app.globalData.accessToken = info.accessToken;
  } catch (e) {
  }
}

const loadLoginInfo = ()=>{
  try {
    var value = wx.getStorageSync(LOGIN_INFO)
    if (value) {
      return value ;
    }
  } catch (e) {
   return undefined ;
  }
}

const hasLogin = ()=>{
  return loadLoginInfo() != undefined ;
}

const simpleLogin = (cb)=>{
  wx.login({
    success:function(res){
      const code = res.code ;
      network.request('mp/auth/simpleLogin', { code: code }, (res) => {
        if (res.data != null && res.data != undefined){
          saveLoginInfo(res.data);
          cb(true);
        }
        else{
          cb(false);
        }
      },err=>{
        cb(false);
      })
    }
  })
}

module.exports = {
  simpleLogin: simpleLogin,
  saveLoginInfo: saveLoginInfo,
  loadLoginInfo: loadLoginInfo,
  hasLogin: hasLogin
}